package com.itheima.controller;

import cn.hutool.core.util.StrUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.itheima.vo.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * date: 2022/5/13 20:50
 *
 * @author daya000
 */
@RestController
@RequestMapping("common")
@Component
public class Commoncontroller {
    @Value("${oss.accessId}")
    private String accessId;

    @Value("${oss.accessKey}")
    private String accessKey;

    @Value("${oss.endpoint}")
    private String endpoint;

    @Value("${oss.bucket}")
    private String bucket;

    @Value("${oss.url}")
    private String url;
    /**
     * 文件上传
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("upload")
    public Result upload(MultipartFile file) throws IOException{

        //获取文件类型 并且判断 是否为空
        String contenType=file.getContentType();
        if (StrUtil.isEmpty(contenType)){
            return new Result(0,null,"类型为空",null);
        }
        //创建一个文件名
        // 命名格式 年月日 + uuid随机 + 后缀名
        String filename=new SimpleDateFormat("yyyy/MM/dd").format(new Date())+
                "/"+ UUID.randomUUID().toString()+"."+contenType.split("/")[1];

        //调用oss的方法
        //build方法（
        //参数
        OSS ossclient = new OSSClientBuilder().build(endpoint,accessId,accessKey);
        ossclient.putObject(bucket,filename,file.getInputStream());
        ossclient.shutdown();

        System.out.println(1);

        return new Result(1,null,url+"/"+filename,null);
    }
}
